package com.project.dao.impl;

import com.project.bean.ReplyBean;
import com.project.bean.UserBean;
import com.project.dao.IReplyDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ReplyDaoImpl extends BaseDao implements IReplyDao {
    @Override
    public void add(ReplyBean replyBean) {
        this.setConnection();
        try {
            ps = con.prepareStatement("insert into t_reply(t_content,t_date,fk_userId,fk_postId) values (?,?,?,?)");
            ps.setObject(1,replyBean.getReplyContent());
            ps.setObject(2,replyBean.getDate());
            ps.setObject(3,replyBean.getUser().getId());
            ps.setObject(4,replyBean.getPost().getId());
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            this.closeConnection();
        }
    }

    @Override
    public List<ReplyBean> findById(Integer id) {
        List<ReplyBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps = con.prepareStatement("select r.*,u.`t_name` from t_reply r,t_user u where u.`pk_userId`=r.`fk_userId` and r.`fk_postId`=? ");
            ps.setObject(1,id);
            rs = ps.executeQuery();
            while (rs.next()){
                ReplyBean replyBean = new ReplyBean();
                replyBean.setReplyContent(rs.getString("t_content"));
                UserBean user = new UserBean();
                user.setUserName(rs.getString("t_name"));
                replyBean.setUser(user);
                String bir = rs.getString("t_date");
                replyBean.setDate(bir!=null? LocalDate.parse(bir):null);
                list.add(replyBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.closeConnection();
        }
        return list;
    }

    public static void main(String[] args) {
        IReplyDao dao = new ReplyDaoImpl();
        System.out.println(dao.findById(1));
    }
}
